;
(function() {
	var wx_pay = require("./pay");
	var wx_core = require("./core");
	var Fiber = require('fibers');
	var hprose = require("hprose");
	// var client = hprose.Client.create('tcp://192.168.31.225:7073/');
	var client = hprose.Client.create('tcp://121.40.72.93:7073/');
	var proxy = client.useService(['payRequestJson', 'jsConfig', 'oauth2Code', 'oauth2AccessToken', "shortUrl"]);

	function WX(appId, appSecret, mchId, key) {
		this.appId = appId;
		this.appSecret = appSecret;
		this.mchId = mchId;
		this.key = key;
		this.access_token = "";
		this.jsapi_ticket = "";
	};
	WX.prototype = {
		getJsApiConfig: function(url) {
			var config = {
				appid: this.appId,
				secret: this.appSecret,
				url: url
			};

			var current_domain = process.domain;
			var self = this;
			return current_domain.run(function() {

				var fiber = Fiber.current;

				proxy.jsConfig(JSON.stringify(config), function(wxConfig) {
					var result = JSON.parse(wxConfig);
					fiber.run(result);
				});
				var result = Fiber.yield();

				setImmediate(function() {
					fiber.run();
				});
				Fiber.yield();
				if (result.stackTrace) {
					console.error(result.message);
					throw (result.message);
				}
				console.log("getJsApiConfig:", config, result);
				return result;
			});
		},
		getWebAccessToken: function(code) {
			console.log("WEIXIN CODE:", code);
			if (!code) {
				throw "GET WEB ACCESS TOKEN ERROR:Code 不可为空";
			}


			var current_domain = process.domain;
			var self = this;
			return current_domain.run(function() {
				var fiber = Fiber.current;

				proxy.oauth2Code(self.appId, self.appSecret, code, function(web_access_token) {
					var result = JSON.parse(web_access_token);
					// console.log(result);
					fiber.run(result);
				});
				var result = Fiber.yield();

				setImmediate(function() {
					fiber.run();
				});
				Fiber.yield();
				if (result.stackTrace) {
					console.error(result.message);
					throw (result.message);
				}
				return result;
			});
		},
		pay_jsUnifiedOrder: function(pay_params) {
			pay_params.type = "JSAPI";
			return this.UnifiedOrder(pay_params);
		},
		pay_nativeUnifiedOrder: function(pay_params) {
			pay_params.type = "NATIVE";
			return this.UnifiedOrder(pay_params);
		},
		pay_appUnifiedOrder: function(pay_params) {
			pay_params.type = "APP";
			return this.UnifiedOrder(pay_params);
		},
		UnifiedOrder: function(pay_params) {
			var params = {
				appid: this.appId,
				mch_id: this.mchId,
				device_info: pay_params.device_info,
				body: pay_params.title,
				detail: pay_params.detail,
				attach: pay_params.attach,
				out_trade_no: pay_params._id,
				// fee_type: "CNY",
				total_fee: parseInt(pay_params.cash * 100),
				spbill_create_ip: pay_params.user_ip,
				goods_tag: pay_params.goods_tag,
				trade_type: (pay_params.type || "JSAPI").toUpperCase(),
				// product_id: "",
				openid: pay_params.openid
			};
			var current_domain = process.domain;
			var self = this;
			return current_domain.run(function() {
				var fiber = Fiber.current;

				console.log("payRequestJson:", JSON.stringify(params), pay_params.pay_notify_security_key);
				proxy.payRequestJson(JSON.stringify(params), self.key, pay_params.pay_notify_security_key, function(wxPayInfo) {
					var result = JSON.parse(wxPayInfo);
					// console.log(result);
					fiber.run(result);
				});
				var result = Fiber.yield();

				setImmediate(function() {
					fiber.run();
				});
				Fiber.yield();
				if (result.stackTrace) {
					console.error(result.message);
					throw (result.message);
				}
				console.log("wxPayInfo:", result);
				return result;
			});
		},
		getUserInfo: function(openid) {
			var current_domain = process.domain || require("domain").create();
			var self = this;
			return current_domain.run(function() { //在hprose的异步函数里头，domain会丢失，所以这时候就要手动处理一下
				var fiber = Fiber.current;
				proxy.oauth2AccessToken(self.appId, openid, function(wx_user_info) {
					var result = JSON.parse(wx_user_info);
					// console.log(result);
					fiber.run(result);
				});
				var result = Fiber.yield();
				setImmediate(function() { //脱离hprose的函数堆栈，摆脱hprose的错误捕捉，然后让错误自由抛出，由domain获取并处理这个错误
					fiber.run();
				});
				Fiber.yield();

				if (result.stackTrace) {
					console.error(result.message);
					throw (result.message);
				}
				return result;
			});
		},
		shortUrl: function(url) {
			var fiber = Fiber.current;
			proxy.shortUrl(this.appId, url, function(long_url_info) {
				long_url_info = JSON.parse(long_url_info);
				fiber.run(long_url_info.short_url);
			});
			var long_url = Fiber.yield();
			return long_url;
		}
	};


	var appId = "wxcf74f930098faee1"
	var appSecret = "77ff4d4b3f861ebacfe1de20c497c411";
	var mchId = "1233472902";
	var Key = "HXCU71nGNU5O4hvQlGSXEuMEMTWQs0HW";
	WX.dotnar_instance = new WX(appId, appSecret, mchId, Key);

	module.exports = WX;

}());
